import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createPage, toast, promptBox,base  } from 'nc-lightapp-front';
import "./index.less"
import DataTable from '../data-table';
import requestApi from './requestApi';
import { get } from 'lodash-es';
const { NCButton, NCModal, NCFormControl  } = base;
import _ from 'lodash';

export default class DataTableList extends Component {

    constructor(props){
        super(props);
        this.state = {
            // 整体数据的arr
            dataArr: [
                // {
                //     "count":"2", //张数
                //     "invoicesum":"875.00", // 金额
                //     "invoiceBag":{ invoiceBag.pk_erminvoice_bag
                //         "pk_erminvoice_bag":"all", // 唯一标志
                //         "bagname":"全部",// 票袋名称
                //         "pk_psndoc":"1001A51000000000301A",
                //         "pk_group":"0001A5100000000012MI",
                //         "pk_org":"0001A5100000000072UO",
                //         "dr":"0",
                //         "ts":"2022-05-1717:15:59",
                //         "valueIndex":{},
                //         "status":"0",
                //         "m_isDirty":false
                //     }
                // }
            ],
            // 当前活动的ID
            activeId: "all",
            // 模糊搜索的值
            fuzzySearchValue: null,
            // 是否显示新增的modal
            showInsertModal: false,
            // 新增加的值
            newValue: null
        };
        // 点击时候改变当前活跃id
        this.handleChangeActiveDataTableList = this.handleChangeActiveDataTableList.bind(this);
        // 删除
        this.handleDeleteDataTableList = this.handleDeleteDataTableList.bind(this);
        // 更新
        this.handleEditDataTableList = this.handleEditDataTableList.bind(this);
        // 修改名字时触发的事件
        this.handleChangeDataTable = this.handleChangeDataTable.bind(this);
        // 点击搜索按钮
        this.handleClickSearch = this.handleClickSearch.bind(this);
        // 确认按钮
        this.beSureBtnClick = this.beSureBtnClick.bind(this);
        // dataTable
        this.onDataTableRef = this.onDataTableRef.bind(this);
        // 新增
        this.handleInsertData = this.handleInsertData.bind(this);
        // 新增改变
        this.handleInsertChangeDataTable = this.handleInsertChangeDataTable.bind(this);
    }

    getMultiLang(){
        let multiLang = {};
        if(this.props && this.props.MutiInit && this.props.MutiInit.getIntl){
            multiLang = this.props.MutiInit.getIntl(2011); 
        }
        return multiLang;
    }

    /**
     * @功能: 刷新数据
     * @作者：Mr.sha
     * @日期：2022-06-02
     * @param {*} e 
     */
    handleRefTableListUpAndIns(params) {
        // {类型，下角标, 后端返回的数据}
        let { sendType, index, data } = params;
        let dataArr = this.state.dataArr;
        let newData = null;
        data.forEach(itemData => {
            let data_pk_erminvoice_bag = get(itemData, "invoiceBag.pk_erminvoice_bag");
            let isEx = false;
            dataArr.forEach(itemDataArr => {
                let arr_pk_erminvoice_bag = get(itemDataArr, "invoiceBag.pk_erminvoice_bag");
                if(data_pk_erminvoice_bag === arr_pk_erminvoice_bag){
                    isEx = true;
                }
            })
            if(!isEx){
                newData = itemData;
            }
        })
        if(!_.isEmpty(newData)){
            dataArr.splice(index, 1, newData);
            this.setState({dataArr: dataArr})
        }


                        // {
                //     "count":"2", //张数
                //     "invoicesum":"875.00", // 金额
                //     "invoiceBag":{ invoiceBag.pk_erminvoice_bag
                //         "pk_erminvoice_bag":"all", // 唯一标志
                //         "bagname":"全部",// 票袋名称
                //         "pk_psndoc":"1001A51000000000301A",
                //         "pk_group":"0001A5100000000012MI",
                //         "pk_org":"0001A5100000000072UO",
                //         "dr":"0",
                //         "ts":"2022-05-1717:15:59",
                //         "valueIndex":{},
                //         "status":"0",
                //         "m_isDirty":false
                //     }
                // }
    }

    /**
     * @功能: 刷新数据
     * @作者：Mr.sha
     * @日期：2022-06-02
     * @param {*} e 
     */
    handleRefTableList(params){
        // let dataArr = this.props.dataArr;
        // // {类型，下角标}
        // let { sendType, index } = params;
        let paramsQuery = {
            ...this.props.params,
            invoiceBagName: ""
        }
        const selectedInvoiceList = []
        const { getCardData } = this.props
        if(getCardData){
            const tableData = getCardData() || []
            for (let row of tableData) {
                if (row && row.values && row.values.pk_erminvoice 
                    // && row.values.pk_erminvoice._display_ !== undefined
                    && row.values.pk_erminvoice.value) {
                    
                    selectedInvoiceList.push({
                        pk_erminvoice: row.values.pk_erminvoice.value,
                        generatetype: row.values.generatetype && row.values.generatetype.value
                    })
                }
            }
        }
        paramsQuery.selectedData = selectedInvoiceList;

        requestApi.bagQuery({
            data: paramsQuery,
            success: (data) => {
                if(Array.isArray(data) && data.length > 0){
                    this.setState({dataArr: data});
                }

                // if(Array.isArray(data) && data.length > 0 && 
                // (sendType === "init" || typeof sendType === "undefined")){
                //     this.setState({dataArr: data});
                // }
                // else if(Array.isArray(data) && data.length > 0 && 
                // (sendType === "insert" || sendType === "update")){
                //     params.data = data;
                //     this.handleRefTableListUpAndIns(params);
                // }
            }
        })
    }

    // 组件将要挂载时触发的函数~~~只执行一次
    componentWillMount() {
    }
    
    // 组件挂载完成触发的函数~~~只执行一次
    componentDidMount(){
        if(this.props && this.props.onRef){
            this.props.onRef(this)
        } 
        this.handleRefTableList({sendType: "init"});  
    }

    /**
     * @功能: 改变当前活跃的对象
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} e 
     */
    handleChangeActiveDataTableList(params){
        this.setState({activeId: params.activeId})
        if(this.props && this.props.handleChangeActiveDataTableList){
            this.props.handleChangeActiveDataTableList(params);
        }
    }

    /**
     * @功能: 获取当前活动的ID
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} e 
     */
    handleBagActiveId() {
        return this.state.activeId;
    }

    /**
     * @功能: 删除方法
     * @作者：Mr.sha
     * @日期：2022-06-02
     * @param {*} e 
     */
    handleDeleteDataTableList(params){
        // { 要删除的pk主键, 下角标 }
        let { pk_erminvoice_bag, index } = params;
        // 删除后新的数组
        let dataArrNew = this.state.dataArr;
        if(_.isEmpty(pk_erminvoice_bag) || pk_erminvoice_bag === ""){
            dataArrNew.splice(index,1);
            return;
        }
        // 要删除数据的下角标
        let deleteIndex = dataArrNew.findIndex(item => {
            return item.invoiceBag.pk_erminvoice_bag === pk_erminvoice_bag;
        });
        if(deleteIndex !== -1){

            requestApi.bagDelete({
                data: {...this.props.params,...params},
                success: (data) => {
                    if(Array.isArray(data) && data.length > 0){
                        // // 删除数据
                        // dataArrNew.splice(deleteIndex,1);
                        // this.setState({dataArr: dataArrNew});
                        this.handleRefTableList({});
                        if(this.props && this.props.handleDeleteDataTableList){
                            this.props.handleDeleteDataTableList(params);
                        }
                        toast({content: data[0]["message"],color:'success'});
                    }
                },
                error: (err) => {
                    this.handleRefTableList({});
                }
            })
        }
    }

    /**
     * @功能: 确认事件
     * @作者：Mr.sha
     * @日期：2022-06-14
     */
    beSureBtnClick() {
        this.handleAddBagToDo();
    }

    /**
     * @功能: 取消事件
     * @作者：Mr.sha
     * @日期：2022-06-14
     */
    cancelBtnClick() {

    }

    /**
     * @功能: 新增确认
     * @作者：Mr.sha
     * @日期：2022-06-14
     */
    handleInsertData(params){
        let { newValue } = params;
        // let noIdList = this.state.dataArr.filter(item => {
        //     return item.invoiceBag.pk_erminvoice_bag === ""
        // });
        // let noIdListLength = 1;
        // if(typeof noIdList !== "undefined"){
        //     noIdListLength = noIdList.length + 1;
        // }
        // const multiLang = this.getMultiLang(); 
        // let dataTableObj = {
        //     "count":"0", //张数  
        //     "invoicesum":"0", // 金额 
        //     "invoiceBag":{
        //         "pk_erminvoice_bag":"", // 唯一标志
        //         "bagname": newValue,// multiLang.get("201103INUP-0025") + "" + (noIdListLength),// 票袋名称
        //         "pk_psndoc":"1001A51000000000301B",
        //         "pk_group":"0001A5100000000012MI",
        //         "pk_org":"0001A5100000000072UO",
        //         "dr":"0",
        //         "ts":"2022-05-17 17:15:59",
        //         "valueIndex":{},
        //         "status":"0",
        //         "m_isDirty":false
        //     }
        // }
        this.handleAddDataTableList({...this.props.params, invoiceBagName: newValue, index: 1});
        // dataArrNew.splice(1, 0, dataTableObj);
        // if(typeof this.state.activeId === "number" && this.state.activeId !== 0) {
        //     this.setState({activeId: this.state.activeId + 1});
        // }
        // this.setState({dataArr: dataArrNew});

    }

    /**
     * @功能: 显示新增的确认框
     * @作者：Mr.sha
     * @日期：2022-06-18
     */
    handleAddBagToDo() {
        this.showInsertConfirm();
    }

    /**
     * @功能: 新增对象
     * @作者：Mr.sha
     * @日期：2022-06-02
     */
    handleAddBag() {
        const multiLang = this.props.MutiInit.getIntl(2011); 
        if(!_.isEmpty(this.state.fuzzySearchValue) && this.state.fuzzySearchValue !== ""){
            promptBox({
                color: 'warning',
                title: multiLang.get("201103INUP-0026"),
                content: '',
                noFooter: false,
                noCancelBtn: false,
                beSureBtnName: multiLang.get("2011-0003"),
                cancelBtnName: multiLang.get("2011-0002"),
                hasCloseBtn: true,
                beSureBtnClick: this.beSureBtnClick,
                cancelBtnClick: this.cancelBtnClick,
                closeByClickBackDrop: true
            })
        }
        else {
            this.handleAddBagToDo();
        }
    }

    /**
     * @功能: 新增~~~~请求后端
     * @作者：Mr.sha
     * @日期：2022-06-06
     * @param {*} e 
     */
     handleAddDataTableList(params){
        
        requestApi.bagInsert({
            data: params,
            success: (data) => {
                if(Array.isArray(data) && data.length > 0){
                    toast({content: data[0]["message"],color:'success'});
                    setTimeout(() => {
                       this.handleRefTableList({sendType: "insert", index: params.index});
                    }, 1000);
                }
            },
            error: (err) => {
                this.handleRefTableList({});
            }
        })
    }
    
    /**
     * @功能: 修改~~~~请求后端
     * @作者：Mr.sha
     * @日期：2022-06-06
     * @param {*} e 
     */
     handleUpdateDataTableList(params){
        requestApi.bagUpdate({
            data: params,
            success: (data) => {
                if(Array.isArray(data) && data.length > 0){
                    toast({content: data[0]["message"],color:'success'});
                    setTimeout(() => {
                        this.handleRefTableList({sendType: "update", index: params.index});
                    }, 1000);
                }
            },
            error: (err) => {
                this.handleRefTableList({sendType: "update", index: params.index});
            }
        })
    }

    /**
     * @功能: 编辑方法
     * @作者：Mr.sha
     * @日期：2022-06-06
     * @param {*} e 
     */
    handleEditDataTableList(params){
        // 票袋pk主键
        let pk_erminvoice_bag = get(params, 'dataTableObj.invoiceBag.pk_erminvoice_bag');
        // 票袋名称
        let bagname = get(params, 'dataTableObj.invoiceBag.bagname');
        
        // 含有pk主键~修改
        if(pk_erminvoice_bag && pk_erminvoice_bag !== ""){
            this.handleUpdateDataTableList({...this.props.params, pk_erminvoice_bag, invoiceBagName: bagname, index: params.index});
        }
        // 不含有pk主键~新增
        else{
            this.handleAddDataTableList({...this.props.params, invoiceBagName: bagname, index: params.index});
        }
    }

    handleChangeDataTable(params) {
       // 数组下角标 ，最新的值，pk主键， 初始化数据
        let {index, newValue, pk_erminvoice_bag, ininValue} = params;
        let dataArrNew = this.state.dataArr;
        if(!_.isElement(newValue) && newValue.length > 20){
            const multiLang = this.props.MutiInit.getIntl(2011); 
            toast({ color: 'warning', content: multiLang.get('201103INUP-0017')}); /*扫描条码未查询到单据*/            
            return ;
        }
        dataArrNew.forEach((item, indexNew) => {
            if(indexNew === index && get(item,"invoiceBag.pk_erminvoice_bag") === pk_erminvoice_bag){
                item.invoiceBag.bagname = newValue;
            }
        })
        this.setState({dataArr: dataArrNew});
    }

    /**
     * @功能: 模糊搜索的事件
     * @作者：Mr.sha
     * @日期：2022-06-14
     * @param {*} e 
     */
    onDataTableRef = (ref) => {
        this.dataTable = ref
    }

     /**
     * @功能: 模糊搜索的事件
     * @作者：Mr.sha
     * @日期：2022-06-14
     * @param {*} e 
     */
    handleClickSearch(params) {
        this.setState(params);
    }

    /**
     * @功能: 显示的数据集合
     * @作者：Mr.sha
     * @日期：2022-06-14
     * @param {*} e 
     */
    getDataList() {
        let dataArr = this.state.dataArr;
        if(!Array.isArray(dataArr)){
            return [];
        }
        if(!_.isEmpty(this.state.fuzzySearchValue) && this.state.fuzzySearchValue !== ""){
            dataArr = dataArr.filter(item => {
                return item.invoiceBag.bagname.indexOf(this.state.fuzzySearchValue) > -1;
            });
        }
        return dataArr;
    }

    getTableListStyleAll() {
        let style = {};
        let { transfertableMainHeight } = this.props;
        if(transfertableMainHeight){
            style = {height: (transfertableMainHeight - 87 - 42) + 'px', 'overflow-y': 'scroll'};
        }
        return style;
    }


    // ====================================================================新增输入框~~~开始
    /**
     * @功能: 显示新增的确认框
     * @作者：Mr.sha
     * @日期：2022-06-18
     */
     showInsertConfirm() {
        this.setState({showInsertModal: true, newValue: null});
    }

    /**
     * @功能: 关闭新增输入框时候触发
     * @作者：Mr.sha
     * @日期：2022-06-18
     */
    closeInsertConfirm() {
        this.setState({showInsertModal: false});
    }

    /**
     * @功能: 新增输入框确认时候触发
     * @作者：Mr.sha
     * @日期：2022-06-18
     */
    confirmInsertModal() {
        this.setState({showInsertModal: false});
        let params = { newValue: this.state.newValue };
        this.handleInsertData(params);
    }

    /**
     * @功能: 新增输入框修改名称时候触发
     * @作者：Mr.sha
     * @日期：2022-06-18
     */
    handleInsertChangeDataTable(value) {
        this.setState({newValue: value});
    }

    /**
     * @功能: 新增的确认框
     * @作者：Mr.sha
     * @日期：2022-06-18
     */
    getInsertConfirmHtml() {
        let multiLang = this.getMultiLang();
        return (
            <div>
                <NCModal size="sm" show={this.state.showInsertModal} onHide={() => {this.closeInsertConfirm()}}>
                    <NCModal.Header closeButton>
                        <NCModal.Title>{ multiLang.get('201102SQFY-0019') }</NCModal.Title>
                    </NCModal.Header>
            
                    <NCModal.Body>
                        <div className = 'insert-modal-main'>
                            <NCFormControl
                                className = 'insert-modal-main-input'
                                placeholder={multiLang.get("201103INUP-0028")}
                                onChange = {this.handleInsertChangeDataTable}
                                value = {this.state.newValue}
                                // onBlur = {this.handleBlurDataTable.bind(this)}
                                // autoFocus = {this.handleAutoFocus()}
                            />
                        </div>
                    </NCModal.Body>
            
                    <NCModal.Footer>
                        <NCButton onClick={() => {this.confirmInsertModal()}} bordered>
                        {multiLang.get("2011-0003")} 
                        </NCButton> 
                        <NCButton onClick={() => {this.closeInsertConfirm()}} colors="secondary" style={{ marginRight: 8 }}>
                        {multiLang.get("2011-0002")} 
                        </NCButton>
                    </NCModal.Footer>
                </NCModal>
            </div>
        );
    }
    // ====================================================================新增输入框~~~结束

    render() {
        return (
            <div className = 'data-table-list' style = {this.getTableListStyleAll()}>
                {
                    this.getDataList().map((item,index) => {
                        return <DataTable 
                                key = {item.invoiceBag.pk_erminvoice_bag + index} 
                                item = {item} 
                                index = {index}
                                activeId = {this.state.activeId} 
                                handleChangeActiveDataTableList = {this.handleChangeActiveDataTableList}
                                handleDeleteDataTableList = {this.handleDeleteDataTableList}
                                handleEditDataTableList = {this.handleEditDataTableList}
                                handleChangeDataTable = {this.handleChangeDataTable}
                                onDataTableRef = {this.onDataTableRef}
                                handleInsertData = {this.handleInsertData}
                            />
                    })
                }
                {this.getInsertConfirmHtml()}
            </div>
        )
    }
}

DataTableList = createPage({
    mutiLangCode: '2011'
})(DataTableList);

ReactDOM.render(<DataTableList />, document.querySelector('#app'))